/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.rocketmq.client.consumer.rebalance;

import java.util.ArrayList;
import java.util.List;
import org.apache.rocketmq.client.consumer.AllocateMessageQueueStrategy;
import org.apache.rocketmq.client.log.ClientLogger;
import org.apache.rocketmq.logging.InternalLogger;
import org.apache.rocketmq.common.message.MessageQueue;

/**
 * Average Hashing queue algorithm
 */
public class AllocateMessageQueueAveragely implements AllocateMessageQueueStrategy {
    private final InternalLogger log = ClientLogger.getLog();

    /**
     * 在进行分配的时候，只有当前一个消费者分配完了，才会分配下一个消费者。例如有消费者A、B，有5个消息队列1、2、3、4、5，计算得到A会分
     * 配3分队列，B会分配2个队列，那么将会先给消费者A分配1、2、3，再给消费者B分配到4、5。
     * @param consumerGroup 当前的消费者组
     * @param currentCID 当前消费者ID
     * @param mqAll topic下的所有队列
     * @param cidAll topic下的所有消费者
     * @return
     */
    @Override
    public List<MessageQueue> allocate(String consumerGroup, String currentCID, List<MessageQueue> mqAll,
        List<String> cidAll) {
        if (currentCID == null || currentCID.length() < 1) {
            throw new IllegalArgumentException("currentCID is empty");
        }
        if (mqAll == null || mqAll.isEmpty()) {
            throw new IllegalArgumentException("mqAll is null or mqAll empty");
        }
        if (cidAll == null || cidAll.isEmpty()) {
            throw new IllegalArgumentException("cidAll is null or cidAll empty");
        }

        List<MessageQueue> result = new ArrayList<MessageQueue>();
        // 如果消费者不包括当前的消费者ID
        // 有可能是当前消费者启动了，但是还没有注册到broker的map里面
        if (!cidAll.contains(currentCID)) {
            // 直接返回，证明不能负载均衡
            log.info("[BUG] ConsumerGroup: {} The consumerId: {} not in cidAll: {}",
                consumerGroup,
                currentCID,
                cidAll);
            return result;
        }
        // 索引位置
        int index = cidAll.indexOf(currentCID);
        // 队列数 % 消费者数 = 剩余的，比如 7 个队列分配给 3 个consumer，那么剩余1个
        int mod = mqAll.size() % cidAll.size();
        int averageSize =
                // 1. 队列数 < 消费者数：每个消费者一个队列
                // 2. 当前消费者在的位置如果 > mod, 证明刚好最后一轮能包括在内，+1
                // 2. 当前消费者在的位置如果 《 mod, 证明刚好最后一轮不包括在内
                // 比如8个队列，3个消费者，那么（0，1，2）分别队列数是（3，3，2），如果当前consumer的index = 1活着2，就能分配到3个队列
            mqAll.size() <= cidAll.size() ? 1 : (mod > 0 && index < mod ? mqAll.size() / cidAll.size()
                + 1 : mqAll.size() / cidAll.size());
        // 计算开始的位置
        // 比如上面的如果是1，那么就是1*3，如果是2，就是2*2+2=6
        int startIndex = (mod > 0 && index < mod) ? index * averageSize : index * averageSize + mod;
        // 取多少个队列，下标（0，1）就是3，下标2就是2
        int range = Math.min(averageSize, mqAll.size() - startIndex);
        for (int i = 0; i < range; i++) {
            result.add(mqAll.get((startIndex + i) % mqAll.size()));
        }
        // 返回结果
        return result;
    }

    @Override
    public String getName() {
        return "AVG";
    }
}
